//晒单提交
exports.ShowAdd = function(req , res){
	var keycode = req.param('key').replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var showNote = req.param('showNote') ? req.param('showNote') : "";
	var sType = req.param('sType') ? req.param('sType') : "";
	if(keycode[2]){
		var async = require('async'),
		mysql = require('mysql'),
		client = mysql.createConnection(myDb),
		express = require('express'),
		formidable = require('formidable'),
		md5 = require('md5'),
		fs = require('fs'),
		async = require('async'),
		AVATAR_UPLOAD_FOLDER = '/show/';
		var form = new formidable.IncomingForm();
		form.encoding = 'utf-8';
		form.uploadDir = 'public' + AVATAR_UPLOAD_FOLDER;
		form.keepExtensions = true;
		//上传限制 3M;
		form.maxFieldsSize = 10 * 1024 * 1024;
		async.waterfall([
			function(callback){
				form.parse(req, function(err, fields, files){
					if (err)
						res.end(JSON.stringify({code:'1'}));
					var extName = '';  //后缀名
					switch (files.file.type) {
						case 'image/pjpeg':
						extName = 'jpg';
						break;
						case 'image/jpeg':
						extName = 'jpg';
						break;
						case 'image/gif':
						extName = 'gif';
						break;						
						case 'image/png':
						extName = 'png';
						break;
						case 'image/x-png':
						extName = 'png';
						break;	 
					}
					if(extName.length > 0){
						var avatarName = '' + md5(Math.random()).substr(0,14) + '.' + extName;
						var newPath = form.uploadDir + avatarName;
						//重命名
						fs.renameSync(files.file.path, newPath);
						callback(null,AVATAR_UPLOAD_FOLDER+avatarName);
					}
					else{
						//文件格式错误;
						res.send(JSON.stringify({code:'3'}));						
					}
				});
			},
			function(a1,callback){
				var theTime = parseInt((new Date()).valueOf()/1000);
				client.connect();
				client.query("use " + myDb.DbName);
				//console.log("INSERT INTO `360_show` (`id`, `uid`, `ImgPath`, `showNote`, `likeNumber`, `dislikeNumber`, `addtime`) VALUES (NULL, '"+ keycode[2] +"', '"+ a1 +"', '" + showNote + "', '0', '0', '"+theTime+"') ");
				client.query("INSERT INTO `360_show` (`id`, `uid`, `ImgPath`, `showNote`, `sType`, `likeNumber`, `dislikeNumber`, `addtime`) VALUES (NULL, '"+ keycode[2] +"', '"+ a1 +"', '" + showNote + "','"+sType+"', '0', '0', '"+theTime+"') ",
					function selectCb(err, returnData, fields){
						if(!err)
							res.send(JSON.stringify({code:"1"}));
						else
							res.send(JSON.stringify({code:'2'}));
					}
				)
			}],
			function (err, result) {
				res.send();
			}
		)
	}
	else{
		res.end(JSON.stringify({code:'2'}));
	}
}

//晒单列表
exports.ShowList = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	if(keycode[2]){
		var async = require('async');
		var mysql = require('mysql');
		var client = mysql.createConnection(myDb);
		client.connect();
		client.query("use " + myDb.DbName);
		//console.log('SELECT `fid` FROM  `360_member_relation` where `uid` = '+keycode[2]+' and `state`=2 ');
		async.waterfall([
			function(callback){
				//获取好友数
				//console.log('SELECT `fid` FROM  `360_member_relation` where `uid` = '+keycode[2]+' and `state`=2 ');
				client.query('SELECT `fid` FROM  `360_member_relation` where (`uid` = '+keycode[2]+' or `fid` = '+keycode[2]+') and `state`=2 ',
					function selectCb(err, returnData){
						if(returnData.length){
							callback(null,returnData);
						}
						else{
							res.send(JSON.stringify({code:'1',data:[]}));
						}
					}
				)
			},
			function(a1 , callback){
				var pid = "";
				for(i=0 ; i< a1.length ; i++){
					pid +=  ","+ a1[i]['fid'];
				}
				pid = pid.substring(1);
				client.query("SELECT b.headPath,a.id as sid,a.likeNumber,a.dislikeNumber,a.ImgPath,a.showNote FROM  `360_show` as a join `360_member` as b where a.uid in("+ pid +") and a.uid =b.id ORDER BY  `addtime` ASC LIMIT 5	",
					function selectCb(err, data, fields){
						if(data.length){
							var retuData = {};
							retuData.code = "1";
							retuData.data = data;
							callback(null,retuData);						
						}
						else
							res.send(JSON.stringify({code:'1',data:[]}));
					}
				)
			},
			function(b1 , callback){
				var MongoClient = require('mongodb').MongoClient;
					for(i in b1.data){
						MongoClient.connect("mongodb://localhost:27017/weimi", function(err, db) {
							db.collection("360_show_opinion", function (err,collection) {
								collection.find({sid:1 , type:1},{headPath:true,_id:false}, {sort: [['addtime', 'asc']]}).limit(5).toArray(function(err,row){
									b1.data[i].likeHeadPath = row;
									if(i == b1.data.length-1)
										res.send(b1);
								})
							})
						})
					}
			}],
			function (err, result) {
				return;
			}
		)
	}
	else
		res.end(JSON.stringify({code:'2'}));
}

//晒单点赞和踩
exports.ShowOpinion = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var sqlField = req.body.type*1 == 1 ? "likeNumber" : "dislikeNumber";
	var type = req.body.type*1 == 1 ? 1 : 2;
	var sid = req.body.sid*1;
	if(keycode[2] && sqlField && sid){
		var mysql = require('mysql');
		var client = mysql.createConnection(myDb);
		var async = require('async');
		client.connect();
		client.query("use " + myDb.DbName);
		async.waterfall([
			function(callback){
				client.query("UPDATE  `360_show` SET  `"+sqlField+"` =  `"+sqlField+"` + 1 WHERE  `id` ="+sid+" LIMIT 1",
					function selectCb(err, returnData){
						if(!err)
							callback(null,true);
						else
							res.send(null,false);
					}
				)
			},
			function(a1,callback){
				if(a1){
					var theTime = parseInt((new Date()).valueOf()/1000);
					var MongoClient = require('mongodb').MongoClient;
						MongoClient.connect("mongodb://localhost:27017/weimi", function(err, db) {
							db.collection("360_show_opinion", function (err,collection) {
								collection.insert({uid:keycode[2]*1,nickName:keycode[3],headPath:keycode[4],type:type,sid:sid,addtime:theTime}, function (err,row) {
									if(row.result.n)
										res.send(JSON.stringify({code:'1'}));
									else
										res.send(JSON.stringify({code:'2'}));
								})
							})				
						})
				}
				else
					res.send(JSON.stringify({code:'2'}));
			}],
			function (err, result) {
				return;
			}
		)
	}
	else
		res.end(JSON.stringify({code:'2'}));
}

//晒单详情和评价
exports.ShowComment = function(req , res){
	var keycode = req.body.key.replace(' ','+');
	var keycode = aes.decode(keycode , key);
	var keycode = keycode.split('|');
	var sid = req.body.sid*1;
	var theTime = parseInt((new Date()).valueOf()/1000);
	var comment = req.body.comment;
	if(keycode[2] && sid && comment){
		var MongoClient = require('mongodb').MongoClient;
			MongoClient.connect("mongodb://localhost:27017/weimi", function(err, db) {
			if(db){
				db.collection("360_show_comment", function (err,collection) {
					collection.insert({uid:keycode[2]*1,nickName:keycode[3],sid:sid,comment:comment,addtime:theTime}, function (err,row) {
						console.log(row);
						if(row.result.n)
							res.send(JSON.stringify({code:'1'}));
						else
							res.send(JSON.stringify({code:'2'}));
					})
				})
			}
			else
				res.send(JSON.stringify({code:'2'}));
		})
		
		//var mysql = require('mysql');
		//var client = mysql.createConnection(myDb);
		//client.connect();
		//client.query("use " + myDb.DbName);
		//client.query("INSERT INTO `360_show_comment` (`id`, `sid`, `uid`, `comment`, `addtime`) VALUES (NULL, '"+sid+"', '"+keycode[2]+"', '"+comment+"', '"+theTime+"')",
		//	function selectCb(err, returnData){
		//		if(!err)
		//			res.send(JSON.stringify({code:'1'}));
		//		else
		//			res.send(JSON.stringify({code:'2'}));
		//	}
		//)
}
	else if(comment==""){
		res.end(JSON.stringify({code:'2'}));
	}
	else{
		res.end(JSON.stringify({code:'3'}));
	}
}